import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { Form, Input, Button, NavBar, Toast } from 'antd-mobile';
import { UserOutlined, LockOutlined } from 'antd-mobile-icons';
import { useRequest } from 'ahooks';
import { postUserLogin } from '../../api/auth';


// 前台登录页面
const Login = () => {
  const navigate = useNavigate();
  const [loading, setLoading] = useState(false);

  // 使用 ahooks 的 useRequest 手动触发登录
  const { runAsync: loginRequest } = useRequest(postUserLogin, {
    manual: true,
  });

  // 处理表单提交
  const onFinish = async (values) => {
    setLoading(true);
    try {
      const res = await loginRequest(values);
      // 登录成功
      const userInfo = {
        ...res
      };
      localStorage.setItem('userInfo', JSON.stringify(userInfo));
      Toast.show({
        icon: 'success',
        content: '登录成功',
      });
      navigate('/home', { replace: true });
    } catch (err) {
      Toast.show({
        icon: 'fail',
        content: err?.message || '用户名或密码错误',
      });
    }
    setLoading(false);
  };

  // 返回首页
  const back = () => {
    navigate('/home');
  };

  return (
    <div className="frontend-container">
      <NavBar onBack={back}>用户登录</NavBar>
      <div style={{ padding: '20px' }}>
        <div style={{ marginBottom: '30px', textAlign: 'center' }}>
          <h2>商城系统</h2>
          <p>登录以获得更好的购物体验</p>
        </div>

        <Form
          layout='horizontal'
          onFinish={onFinish}
          footer={
            <Button
              block
              type='submit'
              color='primary'
              size='large'
              loading={loading}
            >
              登录
            </Button>
          }
        >
          <Form.Item
            name='username'
            label='用户名'
            rules={[{ required: true, message: '请输入用户名' }]}
          >
            <Input placeholder='请输入用户名' clearable />
          </Form.Item>
          <Form.Item
            name='password'
            label='密码'
            rules={[{ required: true, message: '请输入密码' }]}
          >
            <Input placeholder='请输入密码' clearable type='password' />
          </Form.Item>
        </Form>

        <div style={{ marginTop: '16px', textAlign: 'center' }}>
          <Button
            fill='none'
            size='small'
            onClick={() => navigate('/register')}
          >
            还没有账号？去注册
          </Button>
        </div>

        <div style={{ marginTop: '16px', textAlign: 'right' }}>
          <Button 
            fill='none'
            size='small' 
            type="link" onClick={() => navigate('/admin/login')}>
            前往后台管理系统
          </Button>
        </div>
      </div>
    </div>
  );
};

export default Login;